<template>
  <view class="sensor-container">
    <!-- 搜索栏和工具按钮 -->
    <view class="toolbar">
      <input class="search-input" placeholder="请输入属性名称或标识符" />
      <view class="tool-icons">
        <uni-icons type="grid" size="24" />
        <uni-icons type="more" size="24" />
        <uni-icons type="help" size="24" />
      </view>
    </view>

    <!-- 数据卡片组 -->
    <view class="card-group">
      <!-- 温度卡片 -->
      <view class="data-card normal">
        <view class="card-header">
          <uni-icons type="thermometer" size="28" color="#2196F3" />
          <text class="card-title">温度</text>
          <text class="view-options">查看数据 | 查看日志</text>
        </view>
        <view class="card-body">
          <text class="data-value">{{ formatTemperature }}℃</text>
          <text class="timestamp">{{ lastUpdate }}</text>
        </view>
      </view>

      <!-- 湿度卡片 -->
      <view class="data-card normal">
        <view class="card-header">
          <uni-icons type="humidity" size="28" color="#4CAF50" />
          <text class="card-title">湿度</text>
          <text class="view-options">查看数据 | 查看日志</text>
        </view>
        <view class="card-body">
          <text class="data-value">{{ formatHumidity }}%RH</text>
          <text class="timestamp">{{ lastUpdate }}</text>
        </view>
      </view>

      <!-- 光照强度卡片 -->
      <view class="data-card normal">
        <view class="card-header">
          <uni-icons type="sun" size="28" color="#FF9800" />
          <text class="card-title">光照强度</text>
          <text class="view-options">查看数据 | 查看日志</text>
        </view>
        <view class="card-body">
          <text class="data-value">{{ sensorData.LightLux || 0 }}Lux</text>
          <text class="timestamp">{{ lastUpdate }}</text>
        </view>
      </view>

      <!-- 土壤湿度卡片 -->
      <view class="data-card normal">
        <view class="card-header">
          <uni-icons type="soil" size="28" color="#9C27B0" />
          <text class="card-title">土壤湿度</text>
          <text class="view-options">查看数据 | 查看日志</text>
        </view>
        <view class="card-body">
          <text class="data-value">{{ soilHumidityData }}</text>
          <text class="timestamp">{{ lastUpdate }}</text>
        </view>
      </view>
    </view>

    <!-- 状态栏 -->
    <view class="status-bar">
      <text>数据每分钟自动更新 | 当前版本: 1.2.4</text>
      <text v-if="errorMessage" style="color:red;margin-top:10rpx">{{ errorMessage }}</text>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      sensorData: {
        LightLux: 0,
        Humidity: 0,
        soilHumidity: 0,
        temperature: 0
      },
      lastUpdate: '加载中...',
      updateTimer: null,
      dataTimer: null,
      errorMessage: '',
      debugInfo: {} // 新增调试信息存储
    };
  },
  computed: {
    formatTemperature() {
      const temp = this.sensorData.temperature;
      return temp !== undefined && temp !== null ? temp.toFixed(1) : '--';
    },
    formatHumidity() {
      const humid = this.sensorData.Humidity;
      return humid !== undefined && humid !== null ? humid.toFixed(1) : '--';
    },
    soilHumidityData() {
      const soil = this.sensorData.soilHumidity;
      if (soil === undefined || soil === null) return '--';
      
      const percentage = ((soil / 4095) * 100).toFixed(1);
      return `${soil} (${percentage}%)`;
    }
  },
  methods: {
    formatTime(timestamp) {
      const date = new Date(timestamp);
      const pad = n => n.toString().padStart(2, '0');
      return `${date.getFullYear()}/${pad(date.getMonth()+1)}/${pad(date.getDate())} ` +
             `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
    },

    async fetchData() {
      try {
        this.errorMessage = '';
        const res = await uniCloud.callFunction({
          name: 'getSensorData',
          timeout: 15000
        });
        
        console.log('云函数响应:', res);
        
        // 保存调试信息（新增）
        this.debugInfo = {
          requestTime: new Date().toLocaleString(),
          responseData: res.result
        };
        
        if (res.result.code === 200 || res.result.code === 206) {
          // 合并新数据
          this.sensorData = {
            ...this.sensorData,
            ...res.result.data
          };
          
          // 使用服务器返回的时间戳（如果可用）
          const serverTime = Object.values(res.result.timestamps)[0];
          this.lastUpdate = serverTime ? this.formatTime(serverTime) : this.formatTime(Date.now());
          
          console.log('数据更新成功:', this.sensorData);
        } else {
          this.handleError(res.result);
        }
      } catch (err) {
        console.error('调用云函数失败:', err);
        this.errorMessage = '获取数据失败，请检查网络连接';
        uni.showToast({
          title: '获取数据失败',
          icon: 'none'
        });
      }
    },
    
    handleError(result) {
      if (result.error) {
        this.errorMessage = `错误: ${result.error}`;
      } else if (result.message) {
        this.errorMessage = result.message;
      } else {
        this.errorMessage = '未知错误';
      }
      
      uni.showToast({
        title: this.errorMessage,
        icon: 'none'
      });
    },
    
    initTimers() {
      this.fetchData();
      this.dataTimer = setInterval(() => this.fetchData(), 60000);
      this.updateTimer = setInterval(() => {
        this.lastUpdate = this.formatTime(Date.now());
      }, 1000);
    }
  },
  mounted() {
    this.initTimers();
  },
  beforeDestroy() {
    clearInterval(this.dataTimer);
    clearInterval(this.updateTimer);
  }
};
</script>

<style lang="scss">
.sensor-container {
  padding: 20rpx;
  background: #f8f9fa;

  .toolbar {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20rpx;
    padding: 0 20rpx;

    .search-input {
      width: 60%;
      padding: 12rpx;
      border: 1rpx solid #ddd;
      border-radius: 24rpx;
      font-size: 28rpx;
    }

    .tool-icons {
      display: flex;
      gap: 20rpx;
      align-items: center;
    }
  }

  .card-group {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(340rpx, 1fr));
    gap: 20rpx;
    padding: 0 20rpx;
  }

  .data-card {
    background: white;
    border-radius: 16rpx;
    padding: 24rpx;
    box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.08);
    
    .card-header {
      display: flex;
      align-items: center;
      margin-bottom: 16rpx;
      
      .uni-icons {
        margin-right: 12rpx;
      }
      
      .card-title {
        font-size: 30rpx;
        font-weight: 600;
        color: #333;
        flex-grow: 1;
      }
      
      .view-options {
        font-size: 24rpx;
        color: #666;
      }
    }
    
    .card-body {
      .data-value {
        font-size: 44rpx;
        font-weight: 700;
        color: #2c3e50;
        display: block;
        margin-bottom: 8rpx;
      }
      
      .timestamp {
        font-size: 24rpx;
        color: #7f8c8d;
      }
    }
  }

  .status-bar {
    margin-top: 30rpx;
    padding: 20rpx;
    text-align: center;
    font-size: 24rpx;
    color: #666;
    border-top: 1rpx solid #eee;
  }
}
</style>